package com.artup.util.db;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

/**
 * MyBatis 中 BLOB 转换为 String 类型时的字符转码
 * @author hapday
 * 2015年6月19日  上午9:06:22
 */
public class BlobStringConvertTypeHandler extends BaseTypeHandler<String> {  
    private static final String DEFAULT_CHARSET = "utf-8";  	// 字符集
  
    @Override  
    public void setNonNullParameter(PreparedStatement preparedStatement, int i,  
            String parameter, JdbcType jdbcType) throws SQLException {  
        ByteArrayInputStream byteArrayInputStream = null;  
        try {  
            byteArrayInputStream = new ByteArrayInputStream(parameter.getBytes(DEFAULT_CHARSET));  
        } catch (UnsupportedEncodingException e) {  
            throw new RuntimeException("Blob Encoding Error!");  
        }     
        preparedStatement.setBinaryStream(i, byteArrayInputStream, parameter.length());  
    }  
  
    @Override  
    public String getNullableResult(ResultSet resultSet, String columnName)  
            throws SQLException {  
        Blob blob = resultSet.getBlob(columnName);  
        byte [] returnValue = null;  
        if (null != blob) {  
            returnValue = blob.getBytes(1, (int) blob.length());  
        }  
        try {  
        	// 将 BLOB 类型的数据按制定的字符集转换成  String 类型
        	if(null != returnValue){
        		return new String(returnValue, DEFAULT_CHARSET); 		 
        	} else {
        		return null;
        	}
        } catch (UnsupportedEncodingException e) {  
            throw new RuntimeException("Blob Encoding Error!");  
        }  
    }  
  
    @Override  
    public String getNullableResult(CallableStatement callableStatement, int columnIndex)  
            throws SQLException {  
        Blob blob = callableStatement.getBlob(columnIndex);  
        byte[] returnValue = null;  
        if (null != blob) {  
            returnValue = blob.getBytes(1, (int) blob.length());  
        }  
        try {  
        	if(null != returnValue){
        		return new String(returnValue, DEFAULT_CHARSET);  
        	} else {
        		return null;
        	}
        } catch (UnsupportedEncodingException e) {  
            throw new RuntimeException("Blob Encoding Error!");  
        }  
    }

	@Override
	public String getNullableResult(ResultSet resultSet, int arg1)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}  
} 
